<?php
class walletModel extends RPHP_Model
{

    //获取用户提现信息
    public function getWithdrawList($para)
    {
        $amount = 0;
        $where  = "`uid`=" . $this->_user['uid'];

        if (!empty($para['type'])) {
            $where .= " AND `stat`<2";
        }

        if (!empty($para['startDate'])) {
            $start = strtotime($para['startDate'] . " 00:00:00");
        }

        if (!empty($para['endDate'])) {
            $end = strtotime($para['endDate'] . " 23:59:59");
        }

        if (empty($para['startDate']) && empty($para['startDate'])) {
            $start     = strtotime(date(Y) . "-" . date('m') . "-01" . " 00:00:00"); //本月第一天
            $cur_month = date('Y-m-d 23:59:59');
            $end       = strtotime("$cur_month  +1 month -1 day"); //当前最后一天

        }
        if ($start) {
            $where .= " AND `create_time`>=" . $start;
        }

        if ($end) {
            $where .= " AND `create_time`<=" . $end;
        }

        // 排序
        $order = ' `id` DESC';
        //记录总数
        $data   = array();
        $cntsql = "SELECT COUNT(*) FROM {$this->_prefix['primary']}finance_withdraw WHERE " . $where . " ORDER BY " . $order;
        $cnt    = $this->db->getone($cntsql);
        if ($cnt > 0) {

            $sql  = "SELECT * FROM {$this->_prefix['primary']}finance_withdraw WHERE " . $where . " ORDER BY " . $order;
            $data = $this->sql($sql);
            if ($data) {
                foreach ($data as &$r) {

                    if ($r['create_time']) {
                        $r['create_time'] = date('Y-m-d H:i:s', $r['create_time']);
                    }

                    if ($r['stat'] == 0) {
                        $r['stat'] = '<em class="cl">等待处理</em>';
                    } elseif ($r['stat'] == 1) {
                        $r['stat'] = '<em class="cl">处理中</em>';
                    } elseif ($r['stat'] == 2) {
                        $r['stat'] = '<em class="cg">成功</em>';
                    } elseif ($r['stat'] == 3) {
                        $r['stat'] = '<em class="sb">失败</em>';
                    }

                    if ($r['withdraw_type'] == 1) {
                        $r['withdraw_type'] = '微信零钱';
                    } else {
                        $r['withdraw_type'] = '银行卡/账号 尾号' . substr($r['bank_account'], -4, 4);
                    }
                    $amount += $r['money'];
                }
            }
        }

        return array(
            //'page'    => $page,
            //'maxpage' => ceil($cnt / $pagesize),
            //'count'   => $cnt,
            'amount' => $amount,
            'data'   => $data,
            'para'   => $para,
        );
    }

    //保存提现申请
    public function doWithdraw($da)
    {

        $code = 900;
        if ($da['money'] != "") {
            $money = number_format($da['money'], 2, ".", "");
        } else {
            $money = 0;
        }

        if ($da['withdraw_type'] == 2) {
            if ($da['bank']) {
                $sql  = "select * from {$this->_prefix['primary']}member_bank_card where id={$da['bank']} and uid=" . $this->_user['uid'];
                $info = $this->db->getrow($sql);
                $user = $this->getMemberInfo();
                if ($info) {
                    $realname     = $info['account_name'];
                    $bank_sn      = $this->c['bank'][$info['bank_id']];
                    $bank_account = $info['card_number'];
                    $mobile       = $user['mobile'];

                }

            }
        }
        $getSetting    = $this->getSetting();
        $less_withdraw = $getSetting['min_withdraw_money'];

        if ($money > 0 && $money >= $less_withdraw) {

            $balance = $this->getBalance();
            if ($balance['money'] >= $money && $balance['revenue'] >= $money) {

                $charge_fee = number_format(($money * $getSetting['withdraw_percent']), 2, ".", "");
                if ($getSetting['min_withdraw_charge'] > 0 && $charge_fee < $getSetting['min_withdraw_charge']) {
                    $charge_fee = $getSetting['min_withdraw_charge'];
                }

                $pay_money = number_format(($money - $charge_fee), 2, ".", "");
                //开启事务
                $this->db->begin();
                $commit = false;
                $code   = 403;
                //$note          = '申请提现' . $money . '元到'.$realname."[".$bank_sn.$bank_account."]";
                //保存提现信息
                $withdraw_type = intval($da['withdraw_type']);

                if ($withdraw_type == 2) {
                    $sql         = "INSERT INTO {$this->_prefix['primary']}finance_withdraw (`uid`,`money`,`realname`,`mobile`,`bank_sn`,`bank_account`,`charge_fee`,`create_time`,`withdraw_type`) VALUES (" . $this->_user['uid'] . "," . $pay_money . ",'" . $realname . "','" . $mobile . "','" . $bank_sn . "','" . $bank_account . "','" . $charge_fee . "','" . $_SERVER['REQUEST_TIME'] . "'," . $withdraw_type . ")";
                    $txid        = $this->sql($sql);
                    $detail_note = '申请提现' . $money . '元到' . $realname . '[' . $bank_sn . $bank_account . ']，冻结' . $money . '元';
                } else {
                    $detail_note = '申请提现' . $money . '元到微信零钱，冻结' . $money . '元';
                    $sql         = "INSERT INTO {$this->_prefix['primary']}finance_withdraw (`uid`,`money`,`create_time`,`withdraw_type`,`charge_fee`) VALUES (" . $this->_user['uid'] . "," . $pay_money . ",'" . $_SERVER['REQUEST_TIME'] . "'," . $withdraw_type . ",'" . $charge_fee . "')";
                    $txid        = $this->sql($sql);
                }

                if ($txid > 0) {

                    //扣除用户资金
                    $sql = "UPDATE {$this->_prefix['primary']}finance_balance SET `money`=`money`-" . $money . ",`revenue`=`revenue`-" . $money . ",`freeze`=`freeze`+" . $money . ",`last_edit`=" . $_SERVER['REQUEST_TIME'] . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . ",`last_withdraw`=" . $_SERVER['REQUEST_TIME'] . ",`random_num`=" . rand(100000, 999999) . " WHERE `uid`=" . $this->_user['uid'];

                    $baup = $this->sql($sql);
                    if ($baup > 0) {

                        //保存资金明细

                        $event     = 4;
                        $sql       = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`freeze`,`dataid`,`table_name`,`create_time`,`note`) VALUES (" . $this->_user['uid'] . "," . $event . "," . $money . "," . ($balance['money'] - $money) . "," . ($balance['freeze'] + $money) . "," . $txid . ",'finance_withdraw'," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "')";
                        $detail_id = $this->sql($sql);

                        if ($detail_id > 0) {

                            $code   = 200;
                            $commit = true;

                        } else {
                            $code = 411;
                        }

                    } else {
                        $code = 410;
                    }

                } else {
                    $code = 409;
                }

                if ($commit) {
                    $this->db->commit();
                } else {
                    $this->db->rollback();
                }

            } else {
                $code = 408;
            }

        } else {
            $code = 407;
        }

        return array(
            'code' => $code,
        );
    }

    //收支记录
    public function getFinanceDetail($page, $pagesize = 10)
    {

        $sql = "SELECT COUNT(*) AS `cnt` FROM {$this->_prefix['primary']}finance_detail WHERE `uid`=" . $this->_user['uid'];
        $cnt = $this->db->getone($sql);
        if($cnt){
            $start = ($page - 1) * $pagesize;

            $sql = "SELECT * FROM {$this->_prefix['primary']}finance_detail WHERE `uid`=" . $this->_user['uid'] . " AND `cmoney` >0 ORDER BY `id` DESC LIMIT " . $start . "," . $pagesize;

            $rs =  $this->sql($sql);
            if($rs){

                foreach($rs as $k=>$v){

                    $rs[$k]['create_time'] = date("Y-m-d H:i:s",$v['create_time']);
                }
            }
            return array(
                'page'    => $page,
                'maxpage' => ceil($cnt / $pagesize),
                'count'   => $cnt,
                'data'    => $rs,

            );
        }
    }

    //待入账记录
    public function getDRZ($page,$pagesize=12)
    {

        $sql = "SELECT COUNT(*) AS `cnt` FROM {$this->_prefix['primary']}finance_drz WHERE `uid`=" . $this->_user['uid']." AND `status`=0";
        $cnt = $this->db->getone($sql);
        if($cnt){
            $start = ($page - 1) * $pagesize;

            $sql = "SELECT * FROM {$this->_prefix['primary']}finance_drz WHERE `uid`=" . $this->_user['uid'] . " AND `status`=0 ORDER BY `id` DESC LIMIT " . $start . "," . $pagesize;

            $rs =  $this->sql($sql);
            if($rs){

                foreach($rs as $k=>$v){

                    $rs[$k]['create_time'] = date("Y-m-d H:i:s",$v['create_time']);
                }
            }
            return array(
                'page'    => $page,
                'maxpage' => ceil($cnt / $pagesize),
                'count'   => $cnt,
                'data'    => $rs,

            );
        }
        $sql = "";
        return $this->sql($sql);
    }

    //获取佣金明细
    public function getCommissionOrder($page, $pagesize = 20)
    {

        $sql = "SELECT COUNT(*) AS `cnt` FROM {$this->_prefix['primary']}order_info WHERE `pid`=" . $this->_user['uid'] . " AND `pay_status` IN (2,6) AND `shipping_status` NOT IN (7,8)";
        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start  = ($page - 1) * $pagesize;
            $limit  = " LIMIT " . $start . "," . $pagesize;
            $sql    = "SELECT `order_id`,`order_sn`,`add_time`,`is_separate`,`uid` FROM {$this->_prefix['primary']}order_info WHERE `pid`=" . $this->_user['uid'] . " AND `pay_status` IN (2,6) AND `shipping_status` NOT IN (7,8) ORDER BY `add_time` " . $limit;
            $orders = $this->sql($sql);
            if ($orders) {
                foreach ($orders as $key => $val) {
                    $total_price = 0;
                    $sql         = "SELECT `goods_number`,`goods_id`,`goods_price` FROM {$this->_prefix['primary']}order_goods WHERE `order_id` = " . $val['order_id'] . " AND `refund_status` IN (0,5) AND `return_goods_status` IN (0,7)";
                    $order_goods = $this->sql($sql);

                    foreach ($order_goods as $k => $v) {

                        $total_price += $v['goods_number'] * $v['goods_price'];
                    }
                    switch ($val['is_separate']) {
                        case 1;
                            $orders[$key]['is_separate'] = "已分佣";
                            break;
                        case 2;
                            $orders[$key]['is_separate'] = "取消分佣";
                            break;
                        case 3;
                            $orders[$key]['is_separate'] = "无需分佣";
                            break;
                        case 4;
                            $orders[$key]['is_separate'] = "分佣中";
                            break;
                        default:
                            $orders[$key]['is_separate'] = "未分佣";
                            break;
                    }
                    $userDetail                  = $this->getMemberInfo($val['uid']);
                    $orders[$key]['realname']    = $userDetail['realname'];
                    $orders[$key]['pic']         = $userDetail['wechat_headimgurl'];
                    $orders[$key]['total_price'] = $total_price;
                    if ($total_price * 0.03 > 0.01) {
                        $orders[$key]['comm_price'] = number_format($total_price * 0.03, 2, '.', '');

                    } else {
                        $orders[$key]['comm_price'] = 0;
                    }

                    $orders[$key]['add_time'] = date('Y-m-d H:i:s', $val['add_time']);
                }

            }

        }

        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $orders,

        );

    }
    // 获取用户资金
    public function getBalance()
    {
        $sql  = "SELECT * FROM {$this->_prefix['primary']}finance_balance WHERE `uid`=" . $this->_user['uid'];
        $data = $this->db->getrow($sql);
        if ($data['money'] <= 0) {

            $data['money'] = 0.00;
        }

        if ($data['revenue'] <= 0) {

            $data['revenue'] = 0.00;
        }

        return $data;
    }

    //获取用户详情
    public function getUserDetail()
    {
        $sql = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE `uid`=" . $this->_user['uid'];
        return $this->db->getrow($sql);

    }

    //获取用户信息
    public function getMemberInfo($uid = 0)
    {
        if ($uid) {

            $where = " uid=" . $uid;
        } else {
            $where = " uid=" . $this->_user['uid'];
        }
        $sql = "SELECT `uid`,`realname`,`mobile`,`wechat_headimgurl`,`headimgurl`,`pid`,`member_level`,`recode`,`name`,`level_type`,`agent_level`,`maker_level` FROM {$this->_prefix['primary']}member_account WHERE " . $where . " limit 1";
        $rs  = $this->db->getrow($sql);
        if ($rs['headimgurl'] > 0) {

            if ($rs['recode'] == "") {
                $rs['recode'] = $rs['uid'] . "8";
                $sql          = "UPDATE {$this->_prefix['primary']}member_account SET `recode`='" . $rs['recode'] . "' WHERE `uid`=" . $rs['uid'];
                $this->sql($sql);
            }

            $docs = $this->getDocs($rs['headimgurl']);
            if ($docs[$rs['headimgurl']]) {
                $rs['wechat_headimgurl'] = $docs[$rs['headimgurl']];
            }
        }
        return $rs;

    }

    //图片
    public function getDocs($docid)
    {
        if (is_array($docid)) {
            $where = " WHERE `docid` IN (" . implode(",", array_unique($docid)) . ")";
        } else {
            $where = " WHERE `docid`=" . intval($docid);
        }

        $sql = "SELECT `docid`,`filename`,`create_time` FROM {$this->_prefix['primary']}documents " . $where;
        $rs  = $this->sql($sql);
        if ($rs) {
            foreach ($rs as $r) {
                $doc[$r['docid']] = $this->c['doc_host'] . date("Ymd", $r['create_time']) . "/" . date("H", $r['create_time']) . "/" . date("i", $r['create_time']) . "/" . $r['filename'];

            }
            return $doc;
        } else {
            return false;
        }

    }

    //获取商户的金额信息
    public function getShopMoney($shopid)
    {
        if ($shopid) {
            $sql  = "SELECT * FROM {$this->_prefix['primary']}shop_balance where shopid=" . $shopid . " LIMIT 0,1";
            $data = $this->db->getrow($sql);
            return $data;

        }

    }

    //我的银行列表
    public function myBankList()
    {
        $sql  = "select * from {$this->_prefix['primary']}member_bank_card where uid=" . $this->_user['uid'];
        $list = $this->sql($sql);
        foreach ($list as $k => $v) {
            $list[$k]['bank_name'] = $this->c['bank'][$v['bank_id']];

        }

        return $list;
    }

    /**
     * [getBankInfo 获取当前用户的银行卡信息]
     * @param  [type] $bid [description]
     * @return [type]      [description]
     */
    public function getBankInfo($bid)
    {

        $sql  = "select * from {$this->_prefix['primary']}member_bank_card where uid=" . $this->_user['uid'] . " and id=" . $bid;
        $info = $this->db->getrow($sql);
        if ($info) {
            return array("code" => 200, "info" => $info);
        } else {
            return array("code" => 900);
        }

    }

    //添加数据记录
    public function addData($table, $data)
    {
        $code = 900;
        if ($data) {
            $key_str   = "";
            $value_str = "";
            foreach ($data as $k => $v) {
                $k = strip_tags(stripslashes(trim($k)));
                $v = strip_tags(stripslashes(trim($v)));
                if (!empty($v)) {
                    $key_str .= "`" . $k . "`,";
                    $value_str .= "'" . $v . "',";
                }
            }
            if (!empty($key_str) && !empty($value_str)) {

                $key_str   = substr($key_str, 0, strlen($key_str) - 1);
                $value_str = substr($value_str, 0, strlen($value_str) - 1);
                $sql       = "insert into {$this->_prefix['primary']}" . $table . "(" . $key_str . ") values(" . $value_str . ")";
                $id        = $this->sql($sql);
                if ($id) {
                    $code = 200;
                }

            }

        }
        return $code;
    }

    //编辑数据
    public function edit_bank($table, $data)
    {
        $code         = 900;
        $id           = intval($data['id']);
        $bank_id      = intval($data['bank_id']);
        $branch       = trim($data['branch']);
        $card_number  = intval($data['card_number']);
        $account_name = trim($data['account_name']);
        $card_no      = intval($data['card_no']);
        if ($id) {
            $sql  = "UPDATE {$this->_prefix['primary']}$table set `bank_id`=$bank_id,`branch`='" . $branch . " ',`card_number`=$card_number,`account_name`='" . $account_name . " ',`card_no`=$card_no where id=$id and uid=" . $this->_user['uid'];
            $rs   = $this->sql($sql);
            $code = 200;
        }
        return $code;

    }
    //删除银行卡
    public function del_bank($table, $data)
    {
        $code = 900;
        $id   = intval($data['id']);
        if ($id) {
            $sql = "DELETE FROM {$this->_prefix['primary']}$table WHERE id=$id and uid=" . $this->_user['uid'] . " LIMIT 1";
            $rs  = $this->sql($sql);
            if ($rs) {
                $code = 200;
            }
        }
        return $code;

    }

    // 获取设置
    public function getSetting()
    {
        $sql     = "SELECT `setting` FROM {$this->_prefix['primary']}setting ORDER BY `setting_id` DESC LIMIT 1";
        $setting = $this->db->getone($sql);
        if ($setting != "") {
            return json_decode($setting, true);
        }

    }

    // 保存硒豆转金花
    public function subTransfer($da)
    {
        $code = 900;

        $number = intval($da['number']);

        if ($number > 0) {
            $setting = $this->getSetting();
            if ($setting['min_transfer_money'] > 0 && $number < $setting['min_transfer_money']) {
                $code = 401;
                $msg  = '不能小于最低数量';
            } else {
                $balance = $this->getBalance();

                if ($balance['money'] >= $number) {

                    $shouxu = 0;

                    // 计算手续费
                    if ($setting['transfer_percent'] > 0) {
                        $shouxu = $number * $setting['transfer_percent'];
                    }

                    if ($setting['min_transfer_charge'] > 0 && $shouxu < $setting['min_transfer_charge']) {
                        $shouxu = $setting['min_transfer_charge'];
                    }

                    $shide = $number - $shouxu;

                    $this->db->begin();
                    $commit = false;
                    $code   = 403;
                    $msg    = '转换失败';

                    // 更新资金
                    $sql = "UPDATE {$this->_prefix['primary']}finance_balance SET `money`=`money`-" . $number . ",`revenue`=`revenue`-" . $number . ",`gold_money`=`gold_money`+" . $shide . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . ",`random_num`=" . rand(100000, 999999) . " WHERE `uid`=" . $balance['uid'];
                    $rcp = $this->sql($sql);
                    if ($rcp > 0) {
                        // 插入明细
                        $event = 19;
                        $note  = $number . '硒豆转为' . $shide . '金花';

                        $sql = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`create_time`,`note`) VALUES (" . $balance['uid'] . "," . $event . "," . $number . "," . ($balance['money'] - $number) . "," . $_SERVER['REQUEST_TIME'] . ",'" . $note . "')";
                        $rcd = $this->sql($sql);
                        if ($rcd > 0) {
                            $code   = 200;
                            $commit = true;
                        }
                    }

                    if ($commit) {
                        $this->db->commit();
                    } else {
                        $this->db->rollback();
                    }

                } else {
                    $code = 402;
                    $msg  = '可用硒豆不足';
                }
            }
        } else {
            $msg = '数量不能为0';
        }

        return array(
            'code' => $code,
            'msg'  => $msg,
        );
    }

}
